import React, { useCallback, useEffect, useRef, useState } from "react";
import "./index.less";
import ReportForms from "./ReportForms";
import PubSub from 'pubsub-js'; // 组件互相通讯的插件
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { columnsZCAndFZ, columnsLr, columnsCashFlowAndReplenish } from "./ColumnsData";
import { fileExport } from "@/services/cpasRequest";
import { intl } from "@/utils";
import { Upload } from "antd";
import { SelectBox, CheckBox, Button } from "devextreme-react";
import notify from "devextreme/ui/notify";
import { CpasIcon } from "~/public/cpas-ui";
import { getAccountInfo } from "./service";
import { useModel } from "umi";
import CpasTablePupop from "../components/CpasTablePupop";
import '@/pages/components/StyleFile/btnStyle.less';


const FinancialStatementsCheck = (props: any) => {

    const { initialState } = useModel('@@initialState');
    const { dbname, sjnd } = initialState?.curPart as API.CurPart || {};
    const [valIndex, setValIndex] = useState<string>('1');

    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", };
    const DivstyleBox: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "space-between" };
    const Titlestyle: React.CSSProperties = { marginRight: "8px" };
    const [accountData, setAccountData] = useState<any[]>([]);
    const [slectYearData, setSelectYearData] = useState<any>({
        Data_ID: '',
        index: 0
    });
    const [checkBoxVaue, setCheckBoxVaue] = useState<boolean>(false);
    const refsCpasTablePupop = useRef<any>(null);
    const refsReportForms = useRef<any>(null);
    const [valName, setValName] = useState<string>('未审财务报表-资产表');

    const antTabsData = [
        {
            tabName: '资产',
            tabKey: '1',
            propsData: {
                paramsName: '未审财务报表-资产表',
                localStorageName: 'wscwbbFzId',
                bqqm_wss: 'WSS',
                bqqc_wss: 'QCWSS',
                columnData: columnsZCAndFZ
            }
        },
        {
            tabName: '负债',
            tabKey: '2',
            propsData: {
                paramsName: '未审财务报表-负债表',
                localStorageName: 'wscwbbFzId',
                bqqm_wss: 'WSS',
                bqqc_wss: 'QCWSS',
                columnData: columnsZCAndFZ
            }
        },
        {
            tabName: '利润',
            tabKey: '3',
            propsData: {
                paramsName: '未审财务报表-利润表',
                localStorageName: 'wscwbbLrId',
                bqqm_wss: 'WSLJFSE',
                bqqc_wss: 'QCWSLJFSE',
                columnData: columnsLr
            }
        },
        {
            tabName: '现流',
            tabKey: '4',
            propsData: {
                paramsName: '未审财务报表-现金流量表',
                localStorageName: 'wscwbbXjllId',
                bqqm_wss: 'WSLJFSE',
                bqqc_wss: 'QCWSLJFSE',
                columnData: columnsCashFlowAndReplenish
            }
        },
        {
            tabName: '附表',
            tabKey: '5',
            propsData: {
                paramsName: '未审财务报表-现金流补充资料表',
                localStorageName: 'wscwbbXjbczlId',
                bqqm_wss: 'WSLJFSE',
                bqqc_wss: 'QCWSLJFSE',
                columnData: columnsCashFlowAndReplenish
            }
        },
    ];
    // 
    const singleReloadTable = (yearID: string, checkBox: boolean) => {
        if (refsReportForms.current) {
            refsReportForms.current.reloadDevTable(yearID, checkBox, valName);
        }
    }


    const changeTabsKey = useCallback((val: string) => {
        setValIndex(val);
        antTabsData.forEach((item: any) => {
            if (item.tabKey === val) {
                setValName(item.propsData.paramsName);
            }
        })
    }, []);

    // 无差异不显示
    const onValueChangeds = useCallback((e: any) => {
        setCheckBoxVaue(e.value);
    }, []);

    // 获取列表的点击项 
    const onSelectionChangeds = useCallback((e: any) => {
        let selectDefaultIDs = { yearFinancial: e.selectedItem.Data_ID };
        // // 本地存储 持久化数据
        window.localStorage.setItem(`selectFinancialTool_${dbname}`, JSON.stringify(selectDefaultIDs))
        setSelectYearData({
            Data_ID: e.selectedItem.Data_ID,
            index: e.selectedItem.index
        });
    }, []);




    /**
     *获取账套年度数据
     */
    const fetchYearData = useCallback(async () => {
        const auditAdjustId: any = window.localStorage.getItem(`selectFinancialTool_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.yearOpening ?? sjnd;
        let findTemp = -2;
        const res: any = await getAccountInfo({ dbname });
        if (res.success) {
            findTemp = res.data.findIndex((item: any) => {
                return tempYear === item.Data_ID
            });
            const tempIndex = findTemp >= 0 ? findTemp : 0;
            const DataId = res.data[tempIndex]?.Data_ID;
            console.log(DataId, 'DataId----------');


            window.localStorage.setItem(`selectFinancialTool_${dbname}`, JSON.stringify({ yearOpening: DataId }));
            setSelectYearData({
                Data_ID: DataId,
                index: tempIndex
            });
            res.data.forEach((item: any, index: any) => {
                item.index = index
                return item
            });
            setAccountData(res.data);
        }

    }, []);


    useEffect(() => {
        fetchYearData();
    }, []);



    return (<div className="financialStatementsCheck_whole">

        <div style={DivstyleBox}>
            <div style={Divstyle}>
                <div style={Divstyle}>
                    <div style={Titlestyle}>{intl('report.subject.account', '账套:')}</div>
                    <SelectBox
                        width={200}
                        dataSource={accountData}
                        displayExpr='displayName'
                        valueExpr='displayName'
                        value={accountData[slectYearData.index || 0]?.displayName ?? ""}
                        onSelectionChanged={onSelectionChangeds}
                        dropDownOptions={
                            { width: '400px' }
                        }
                    />
                </div>
                <div style={{ ...Divstyle, marginLeft: 15 }}>
                    <CheckBox className='SubjectsCheckBox' onValueChanged={onValueChangeds} /><span style={{ marginLeft: "5px" }}>1无差异不显示</span>

                </div>
            </div>
            <div>
                <Button type='default' className="defaultBtn"
                    text='导出模板' onClick={async () => {
                        const result = await window.electronComponents.openDirectoryDialog();
                        if (!result.canceled) {
                            const params = {
                                srcDir: "AppData/Files/财务报表模板",
                                targetDir: result.filePaths[0],
                                files: ['财务报表.xlsx']
                            }
                            try {
                                const resFile = await fileExport(params);
                                if (resFile.ok) {
                                    notify({ message: `导出模板成功！`, position: 'top center' }, "success", 1500);
                                } else {
                                    notify({ message: `导出模板失败！`, position: 'top center' }, "error", 1000);
                                }
                            } catch (error) {
                                notify({ message: `导出模板失败！`, position: 'top center' }, "error", 1000);
                            }
                        }
                    }} />
                {/* <Upload
                    name={"file"}
                    maxCount={1}
                    beforeUpload={(file: any) => {
                        const cpasTableName = `${slectYearData.Data_ID}-${valName}`;
                        refsCpasTablePupop.current.showCpasTablePupop(file, cpasTableName);
                        return false;
                    }}
                    showUploadList={false}
                    accept=".xlsx"
                >
                    <Button type='default' className="defaultBtn" text='财务报表导入' />
                </Upload> */}
                <Button
                    className="defaultReloadBtnWhite"
                    render={() => <CpasIcon type='icon-refresh' fontSize={16} />}
                    onClick={() => {
                        singleReloadTable(slectYearData.Data_ID, checkBoxVaue);
                    }} />
            </div>

        </div>
        <AntTabs defaultActiveKey="1"
            onChange={(val: string) => { changeTabsKey(val) }} activeKey={valIndex}>
            {
                antTabsData.map(item => (
                    <AntTabs.TabPane tab={item.tabName} key={item.tabKey} >
                        <ReportForms ref={refsReportForms} devTableProps={item.propsData} slectYearData={{ ...slectYearData, checkBoxVaue }} />
                    </AntTabs.TabPane>
                ))
            }
        </AntTabs>

        <CpasTablePupop
            ref={refsCpasTablePupop}
            reloadDevTable={() => {
                singleReloadTable(slectYearData.Data_ID, checkBoxVaue);
            }}
        />
    </div >
    )
}
export default FinancialStatementsCheck;